package com.xiaoq.share;

import java.io.BufferedWriter;
import java.io.FileOutputStream;
import java.io.OutputStreamWriter;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.http.MediaType;
import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import com.xiaoq.coms.GenericDataResponse;
import com.xiaoq.coms.GenericResponse;
import com.xiaoq.share.vo.ContentStaticVo;

import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import io.swagger.annotations.ApiResponse;
import io.swagger.annotations.ApiResponses;

@Api(tags={"头条内容静态化"})
@RestController
@RequestMapping("/api/v1/share")
public class ContentCollectionEndpoint {
	
	@Value("${staticPath}")
	private String staticPath;
	
	private static final class ContentStaticResponse extends GenericDataResponse<String> {}
	
	private static Logger LOG = LoggerFactory.getLogger(ContentCollectionEndpoint.class);
	
	@ApiOperation(value = "对内容静态化", notes = "对内容静态化")
	@ApiResponses({ @ApiResponse(code = 200, response = ContentStaticResponse.class, message = "对内容静态化") })
	@PostMapping(value = "/content", produces = { MediaType.APPLICATION_JSON_UTF8_VALUE })
	public ResponseEntity<?> contentStatic(
			@RequestBody ContentStaticVo contentStaticVo) {
		String fileName = System.currentTimeMillis()+".html";
		String path = staticPath+"/"+fileName;
		String url = "https://www.xiaoq.online/content/"+fileName;
		String content = contentStaticVo.getContent();
	    try {
	    	
	    	FileOutputStream writerStream = new FileOutputStream(path);    
	    	BufferedWriter writer = new BufferedWriter(new OutputStreamWriter(writerStream, "UTF-8")); 
	    	writer.write(content);
	    	writer.flush();
	    	writer.close(); 
	    	writerStream.close();
	    } catch (Exception e) {
	    	LOG.error(e.getMessage());
	    	return GenericResponse.ng("内容静态化成功");
	    }
		return ContentStaticResponse.okWithData(url);

	}

}
